package com.zyt.download;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@WebServlet("/downloadDemo")
public class DownloadDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 超链接指向的资源如果可以被浏览器解析，浏览器会默认打开
        // 如果需要下载，需要设置响应头，使用下载的方式，类似如下的header
        // * content-disposition:attachment;filename=xxx

        String fileName = req.getParameter("filename");

        // 1、设置Header
        resp.setContentType(this.getServletContext().getMimeType(fileName));
        resp.setHeader("content-disposition"," attachment;filename="+fileName);

        // 2、使用流读取文件
        String filePath = this.getServletContext().getRealPath("images/"+fileName);
        BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(filePath));

        // 3、写入response的输出流
        byte[] buff = new byte[1024 * 8];
        int len = 0;
        while ((len = inputStream.read(buff)) != -1) {
            resp.getOutputStream().write(buff);
        }

        // 4、关闭输出流
        inputStream.close();
    }
}
